﻿using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Topro.Util
{
    /// <summary>
    /// Web工具
    /// </summary>
    public class WebUtil
    {
        /// <summary>
        /// 检查是否为本地地址正则
        /// </summary>
        private static Regex checkUrlRegex = null;

        /// <summary>
        /// 检查地址是否为本地地址（包含相对路径和绝对路径，例如：xxx://开头的都不是本地地址）
        /// </summary>
        /// <param name="url"></param>
        /// <returns>bool</returns>
        /// <remarks>2013-04-03 杨合余 创建</remarks>
        /// <remarks>2013-06-08 罗雄伟 重构</remarks>
        public static bool IsLocalUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;

            if (url.StartsWith("/"))
                return true;

            //先判断前缀
            if (
                url.StartsWith("http://", true, null)
                || url.StartsWith("https://", true, null)
                || url.StartsWith("ftp://", true, null)
                )
            {
                return false;
            }
            if (checkUrlRegex == null)
                checkUrlRegex = new Regex(@"^\w+://.*$", RegexOptions.IgnoreCase);

            return !checkUrlRegex.IsMatch(url);
        }

        /// <summary>
        /// 生成指定长度随机数字
        /// </summary>
        /// <param name="length">生成长度</param>
        /// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param>
        /// <returns>指定长度的随机数</returns>
        /// <remarks>2013－07-24 苟治国 创建</remarks>
        public static string Number(int length, bool sleep)
        {
            if (sleep)
                System.Threading.Thread.Sleep(3);
            string result = "";
            Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                result += random.Next(10).ToString();
            }
            return result;
        }

        /// <summary>
        /// 隐藏手机号中间4位
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <returns>格式:135****0534</returns>
        /// <remarks>2013-4-2 杨合余 添加</remarks>
        public static string HideMobilePhone(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
                return "";
            string pattern = @"(1[3,5,8]\d)(\d{4})(\d{4})";
            Regex reg = new Regex(pattern);
            return reg.Replace(phone, "$1****$3");
        }

        /// <summary>
        /// 将时间转换为Unix格式的刻度
        /// </summary>
        /// <param name="time"></param>
        /// <returns>刻度</returns>
        /// <remarks>2014-1-21 杨合余 添加注释</remarks>
        public static long ConvertDateTimeUnix(System.DateTime time)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = time;
            TimeSpan t = (dtNow - dtStart);
            return (long)t.TotalSeconds * 1000;
        }

        /// <summary>     
        /// 去除HTML标记     
        /// </summary>     
        /// <param name="strHtml">包括HTML的源码 </param>     
        /// <returns>已经去除后的文字</returns>  
        /// <remarks>2013－11-22 杨晗 创建</remarks> 
        public static string StripHTML(string strHtml)
        {
            string[] aryReg =
                {
                    @"<script[^>]*?>.*?</script>",
                    @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
                    @"([ ])[\s]+",
                    @"&(quot|#34);",
                    @"&(amp|#38);",
                    @"&(lt|#60);",
                    @"&(gt|#62);",
                    @"&(nbsp|#160);",
                    @"&(iexcl|#161);",
                    @"&(cent|#162);",
                    @"&(pound|#163);",
                    @"&(copy|#169);",
                    @"&#(\d+);",
                    @"-->",
                    @"<!--.* "
                };
            string[] aryRep =
                {
                    "",
                    "",
                    "",
                    "\"",
                    "&",
                    "<",
                    ">",
                    " ",
                    "\xa1", //chr(161),    
                    "\xa2", //chr(162),    
                    "\xa3", //chr(163),     
                    "\xa9", //chr(169),        
                    "",
                    " ",
                    ""
                };
            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }
            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace(" ", "");
            return strOutput;
        }

        /// <summary>
        /// 判断访问是否来至于手机等设备
        /// </summary>
        /// <param name="AgentStr">UserAgent参数</param>
        /// <returns>是否来至手机访问</returns>
        /// <remarks>2014-09-23 张晓辉 创建</remarks> 
        public static bool IsComeFromMobile(string AgentStr)
        {
            var AgentRegex = new System.Text.RegularExpressions.Regex(@"iemobile|iphone|ipod|android|nokia|sonyericsson|blackberry|samsung|sec\-|windows ce|motorola|mot\-|up.b|midp\-", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            if (string.IsNullOrEmpty(AgentStr) || AgentRegex.IsMatch(AgentStr))
                return true;
            return false;
        }
    }
}
